package com.example.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.admin.connect.AdminConnect;
import com.example.admin.dao.AdChannelMapper;
import com.example.admin.dao.AdSensitiveMapper;
import com.example.admin.feign.WmNewFeign;
import com.example.admin.service.WmNewsService;
import com.usian.common.alibaba.GreeTextScanUtil;
import com.usian.common.alibaba.GreenImageScanUtil;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.admin.pojos.AdSensitive;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmNews;
import com.usian.utils.common.SensitiveWordUtil;
import com.usian.utils.common.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl implements WmNewsService {
    @Autowired
    private WmNewFeign wmNewFeign;
    @Autowired
    private GreenImageScanUtil greenImageScanUtil;
    @Autowired
    private GreeTextScanUtil greeTextScanUtil;
    @Autowired
    private AdSensitiveMapper adSensitiveMapper;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private AdChannelMapper adChannelMapper;


    @Override
    public ResponseResult wmNewsChecked(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = wmNewFeign.getWmNewsById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wmNews.getStatus()==4){
            return ResponseResult.errorResult(505,"人工审核不通过");
        }
        if (wmNews.getStatus()==8 && wmNews.getPublishTime().getTime()<= System.currentTimeMillis()){
            /**
             * 添加文章信息到文章的微服务
             * 修改自媒体的状态信息
             */
            wmNewFeign.updateWmNews(wmNews,8);
        }
        if (wmNews.getStatus()==1){
            Map<String, Object> map = getTextAndImage(wmNews);
            String imageResult = "pass";
            String textResult = "pass";
            if (!map.get("text").equals("")){
                textResult = checkeContext((String) map.get("text"));
            }
            if (!CollectionUtils.isEmpty( (List<String>) map.get("image"))){
                 imageResult = checkImage((List<String>) map.get("image"));
            }
            if (textResult.equals(AdminConnect.CHECK_FAIL) || imageResult.equals(AdminConnect.CHECK_FAIL)){
                wmNewFeign.updateWmNews(wmNews,2);
                return  ResponseResult.errorResult(AppHttpCodeEnum.NO_FAIL);
            }
            if (textResult.equals(AdminConnect.CHECK_REVIEW) || imageResult.equals(AdminConnect.CHECK_REVIEW)){
                wmNewFeign.updateWmNews(wmNews,3);
                return ResponseResult.errorResult(AppHttpCodeEnum.PERSON_FAIL);
            }
            System.out.println("111111111111");
            wmNewFeign.updateWmNews(wmNews,8);
            return ResponseResult.okResult("审核通过");
        }
        return null;
    }

    @Override
    public String wmNewsChannelNameById(Integer id) {
        LambdaQueryWrapper<AdChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdChannel::getId,id);
        return adChannelMapper.selectOne(queryWrapper).getName();
    }

    public String checkeContext(String connect){
        List<AdSensitive> adSensitives = adSensitiveMapper.selectList(null);
        List<String> collect = adSensitives.stream().map(AdSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(collect);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(connect);
        if (map.size()>0){
            return "block";
        }
        try {
            return greeTextScanUtil.greenTextScan(connect);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "block";
    }

    public String checkImage(List<String> imageList){
        List<byte[]> bytes = new ArrayList<>();
        try {
            for (String s : imageList) {
                HashMap<String, String> map = StringUtils.subStringPath(s);
                byte[] imgByte = fastDFSClient.download(map.get("group"), map.get("imgPath"));
                bytes.add(imgByte);
            }
            return  greenImageScanUtil.imageScan(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "block";
    }

    public Map<String,Object> getTextAndImage(WmNews wmNews){
        if (wmNews.getContent().equals("") && wmNews.getImages().equals("")){
            return null;
        }
        Map<String,Object> map = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        List<String> imageList = new ArrayList<>();
        if (!wmNews.getContent().equals("")){
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map1 : maps) {
                if (map1.get("type").equals("text")){
                    stringBuilder.append(map1.get("value"));
                }
                if (map1.get("type").equals("image")){
                    String value = StringUtils.substringPath((String) map1.get("value"));
                    imageList.add(value);
                }
            }
        }
        if (!wmNews.getImages().equals("")){
            String[] split = wmNews.getImages().split(",");
            imageList.addAll(Arrays.asList(split));
        }
        if (!stringBuilder.toString().equals("")){
            map.put("text",stringBuilder.toString());
        }
        if (!CollectionUtils.isEmpty(imageList)){
            map.put("image",imageList);
        }
        return map;
    }

}
